import navBottom from '../common/nav-bottom.vue'
import CONSTANT from '@/common/constants.js';
import http from '@/common/http.js';
import './payment.scss';
import XHeader from 'vux/src/components/x-header/index.vue'
import Group from 'vux/src/components/group/index.vue'
import XSwitch from 'vux/src/components/x-switch/index.vue'
import wx from 'weixin-js-sdk'

// var CodeSTD = window.CodeSTD || {};
// window.CodeSTD = CodeSTD;
// /**
//  * 创建Form表单
//  * @author 王成委
//  * @param config Object
//  *  <p>url:form的Action，提交的后台地址</p>
//  *  <p>method:使用POST还是GET提交表单</p>
//  *  <p>params:参数 K-V</p>
//  * @return Form
//  */
// CodeSTD.form = function (config) {
//   config = config || {}
//
//   var url = config.url,
//     method = config.method || 'GET',
//     params = config.params || {}
//
//   var form = document.createElement('form')
//   form.action = url
//   form.method = method
//
//   for (var param in params) {
//     var value = params[param],
//       input = document.createElement('input')
//
//     input.type = 'hidden'
//     input.name = param
//     input.value = value
//
//     form.appendChild(input)
//   }
//
//   return form
// }
export default {
  name: 'payment',
  components: {navBottom, XHeader, Group, XSwitch},
  data () {
    return {
      ids: [],
      id: '',
      money: '',
      list: [],
      accept: '',
      totalMoneys: '',
      theme: '',
      // 是否公开按钮
      ifshow: true,
      isGongkai: '公开',

      // 个人捐款
      username: '',
      name: '',
      idCard: '',
      telephone: '',
      content: '',
      userId: '',
      event_id: '',
      openid: '',
      paySignObj: '',
      witchOne: '',
      eventAbstract: '',
      isTh: 2,
      isNiming: 2,
      together_id: '',
      is_together:null,
      product_id: '',
      receiptId: '',
      // 请求判断参数
      requestSecret: '',
      requestSecretEndTime: '',
      currentDateLong: ''
    }
  },
  watch: {
    ifshow: function () {
      if (this.ifshow == true) {
        this.isGongkai = '公开'
      } else {
        this.isGongkai = '匿名'
      }
    }
  },
  mounted () {
    this.wx.hideMenuItems({
      menuList: ['menuItem:copyUrl']
    })
    if (this.$emit('ifOpenid')) {
      this.$emit('ifOpenid', this.$route.path)
    }
    if (this.$emit('ShareAppMessage')) {
      this.$emit('ShareAppMessage', '亲青筹', '“亲青筹”由浙江团省委、青基会发起设立，通过众筹善款，服务青少年成长。', 'http://www.qqchou.org/a/wxinterface/wxOAuth', this.imageUrl.imageUrl+'/userfiles/2/images/1513911875.png')
    }
    console.log(typeof (this.$route.query.type) == 'string')
    var urlaa = window.location.href
    console.log(urlaa)
    var json = {time: new Date().getTime()}
    var arrbb = urlaa.split('?#')[1]
    var arr = urlaa.split('#')
    if (!arrbb) {
      window.location.href = (json, ' ', arr[0] + '?#' + arr[1])
    }
    console.log(arr)

    this.openid = window.sessionStorage.getItem('openid')
    this.userId = window.sessionStorage.getItem('userId')
    this.event_id = this.$route.query.event_id
    this.money = this.$route.query.money
    this.witchOne = this.$route.query.witchOne
    if (this.$route.query.together_id) {
      this.together_id = this.$route.query.together_id
    }
    if (this.$route.query.is_together) {
      this.is_together = this.$route.query.is_together
    }
    if (this.$route.query.witchOne == 'piliang') {
      this.ids = this.$route.query.ids
      // this.money = this.$route.query.money
      console.log('调用批量捐接口')
      http.post(CONSTANT.GO_DONATE, {ids: this.ids, money: this.money}, (res) => {
        console.log(res)
        if (res.code == 200) {
          this.list = res.obj.list
          this.accept = res.obj.accept
          this.money = res.obj.totalMoneys
          this.theme = res.obj.theme
        } else {
          console.log('出错了 code不是200了')
        }
      })
    } else {
      // this.GetRequest()
      var type = 0
      if (this.$route.query.type) {
        console.log('一对一捐助')
        type = 1
      }
      console.log('调用个人捐款接口')
      http.post(CONSTANT.SINGLE_DONATE, {
        userId: this.userId,
        event_id: this.event_id,
        money: this.money,
        type: type
      }, (res) => {
        if (res.code == 200) {
          console.log(res)
          this.list = res.obj.list
          this.accept = res.obj.accept
          this.money = res.obj.money
          this.theme = res.obj.theme
          this.eventAbstract = res.obj.eventAbstract
          this.isTh = res.obj.isTh
        }
      })
    }
  },
  methods: {
    getcurrentDateLong () {
      // 获取当前时间的转为long型
      var nowDate = new Date()
      var year = nowDate.getFullYear()
      var month = nowDate.getMonth() + 1
      var today = nowDate.getDate()
      var hours = nowDate.getHours()
      var minutes = nowDate.getMinutes()
      var seconds = nowDate.getSeconds()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (today >= 1 && today <= 9) {
        today = '0' + today
      }
      var currentdate = year + '-' + month + '-' + today + ' ' + hours + ':' + minutes + ':' + seconds
      var currentDateLong = new Date(currentdate.replace(new RegExp('-', 'gm'), '/')).getTime()
      this.currentDateLong = currentDateLong
      console.log('当前时间的long型:', this.currentDateLong)
    },
    callPay () {
      var _this = this
      wx.chooseWXPay({
        timestamp: _this.paySignObj.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        nonceStr: _this.paySignObj.nonceStr, // 支付签名随机串，不长于 32 位
        package: _this.paySignObj.packageStr, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
        signType: "MD5", // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
        paySign: _this.paySignObj.paySign, // 支付签名
        success: function (res) {
          // 支付成功后的回调函数
          // window.history.go(-1)
          if (_this.isTh == 1) {
            window.location.href = 'http://www.qqchou.org/a/wxinterface/wxOAuth?category=3&event_id=' + _this.event_id
          } else {
            window.location.href = 'http://www.qqchou.org/a/wxinterface/wxOAuth'
          }
        },
        fail: function(res){// 支付失败回调函数
        	alert('fail, 支付失败请重新下单')
            window.location.href = 'http://www.qqchou.org/a/wxinterface/wxOAuth?category=3&event_id=' + _this.event_id
        },
        cencel: function () {
        	alert('cancel, 支付失败请重新下单')
        	window.location.href = 'http://www.qqchou.org/a/wxinterface/wxOAuth?category=3&event_id=' + _this.event_id
        }
      })
      // wx.error(function(res){
      // 	alert('error, 支付失败请重新下单')
    	// 	alert(res.err_msg);
    	// 	window.location.href = 'http://www.qqchou.org/a/wxinterface/wxOAuth?category=3&event_id=' + this.event_id
		// 	});
    },
    weixinXD () {
      this.requestSecret = window.sessionStorage.getItem('requestSecret')
      if (this.isGongkai == '公开') {
        this.isNiming = 2
      } else {
        this.isNiming = 1
      }
      if (this.$route.query.witchOne == 'piliang') {
        this.ids = this.$route.query.ids
        // this.money = this.$route.query.money
        console.log('调用批量捐创建订单接口')
        var moneys = ''
        if (typeof this.ids == 'string') {
          moneys = this.money
        } else {
          moneys = this.money / this.ids.length
        }
        console.log(moneys)
        http.post(CONSTANT.BATCH_ADD, {
          money: moneys,
          ids: this.ids,
          userId: this.userId,
          isNiming: this.isNiming
        }, (res) => {
          console.log(res)
          this.product_id = res.obj.product_id
          this.weixinConfig()
        })
      } else {
        var type = 0
        var eventid = ''
        if (this.$route.query.type) {
          console.log('一对一捐助')
          type = 1
          eventid = this.$route.query.student_id
        } else {
          eventid = this.event_id
        }
        console.log('调用个人创建订单接口')
        console.log('eventid', eventid)
        if (!this.is_together) {
          this.is_together = 0;
        }
        http.post(CONSTANT.RECEIPT_ADD, {
          money: this.money,
          event_id: eventid,
          userId: this.userId,
          isNiming: this.isNiming,
          together_id: this.together_id,
          is_together:this.is_together,
          type: type
        }, (res) => {
          console.log(res)
          this.product_id = res.obj.product_id
          this.receiptId = res.obj.receiptId
          if (this.$route.query.type) {
            console.log('一对一捐助')
            type = 1
            eventid = this.$route.query.student_id
            var oname = this.$route.query.name
            var oidCard = this.$route.query.idCard
            var otelephone = this.$route.query.telephone
            var ocontent = this.$route.query.content
            var oaddress = this.$route.query.address
            if (typeof oname == 'undefined') {
              oname = ''
            }
            if (typeof oidCard == 'undefined') {
              oidCard = ''
            }
            if (typeof otelephone == 'undefined') {
              otelephone = ''
            }
            if (typeof ocontent == 'undefined') {
              ocontent = ''
            }
            if (typeof oaddress == 'undefined') {
              oaddress = ''
            }
            http.post(CONSTANT.USER_WORD, {userId: this.userId, name: oname, idCard: oidCard, telephone: otelephone, address: oaddress, student_id: eventid, content: ocontent}, (res) => {
              console.log('liuyan', res)
            })
          } else {
            var rname = this.$route.query.name
            var ridCard = this.$route.query.idCard
            var rtelephone = this.$route.query.telephone
            var rcontent = this.$route.query.content
            var raddress = this.$route.query.address
            if (typeof rname == 'undefined') {
              rname = ''
            }
            if (typeof ridCard == 'undefined') {
              ridCard = ''
            }
            if (typeof rtelephone == 'undefined') {
              rtelephone = ''
            }
            if (typeof rcontent == 'undefined') {
              rcontent = ''
            }
            if (typeof raddress == 'undefined') {
              raddress = ''
            }
            http.post(CONSTANT.USER_MESSAGE, {receiptId: this.receiptId, userId: this.userId, name: rname, idCard: ridCard, telephone: rtelephone, address: raddress, event_id: this.event_id, content: rcontent}, (res) => {
              console.log(res)
            })

          }
          this.weixinConfig()
        })
      }
    },
    weixinConfig () {
      let thisPageUrl = window.location.href.split('#')[0]
      // console.log(thisPageUrl)
      console.log('微信授权url****' + thisPageUrl)
      http.post(CONSTANT.WXCONFIG, {'url': thisPageUrl}, (res) => {
        if (res.code == 200) {
          console.log('config参数已返回')
          console.log(res)
          this.wx.config({
            "debug": false,
            "appId": res.obj.appid,
            "timestamp": res.obj.timestamp,
            "nonceStr": res.obj.nonceStr,
            "signature": res.obj.signature,
            "jsApiList": ['chooseWXPay']
          })
          console.log('调用微信支付')
          console.log(this.requestSecret)
          console.log(this.product_id)

          // var form = new CodeSTD.form({
          //   url: 'http://etzx.hztangong.com/payment',
          //   method: 'POST',
          //   params: {
          //     appKey: '402880e75f1520d3015f152167180000',
          //     requestSecret: this.requestSecret,
          //     type: '11',
          //     openid: this.openid,
          //     callBackUrl: encodeURI(CONSTANT.RECEIPT_ACHIEVE),
          //     orderInfo: '{"count": 1,"product_id":"' + this.product_id + '", "product_name": "' + this.theme + '","product_detail": "' + this.eventAbstract + '","price":' + this.money + '}'
          //   }
          // })
          // console.log(form)
          // document.body.appendChild(form)
          // form.submit()
          // form = null
          http.post('http://www.qqchou.org/zfzx/api', {'appKey': '402880e75f1520d3015f152167180000', 'requestSecret': this.requestSecret, 'type': '11', product_id: this.product_id, openid: this.openid, callBackUrl: encodeURI(CONSTANT.RECEIPT_ACHIEVE), 'orderInfo': '{"count": 1,"product_id":"' + this.product_id + '", "product_name": "' + this.theme + '","product_detail": "' + this.eventAbstract + '","price":' + this.money + '}'}, (res) => {
            console.log(res)
            if (res.code == 200) {
              this.paySignObj = res.obj
              this.callPay()
            } else {
              if (res.code == 502) {
                alert('该学生已经被资助，感谢您的支持！')
              } else {
                alert('提交订单失败！')
              }
            }
          })
        }
      })
    },
    getrequestSecret (e) {
      http.post('http://www.qqchou.org/zfzx/refresh_key', {'appKey': '402880e75f1520d3015f152167180000'}, (res) => {
        console.log('refresh_key')
        console.log(res)
        if (res.code == 200) {
          this.requestSecret = res.obj.requestSecret
          this.requestSecretEndTime = res.obj.requestSecretEndTime
          window.sessionStorage.setItem('requestSecret', res.obj.requestSecret)
          window.sessionStorage.setItem('requestSecretEndTime', res.obj.requestSecretEndTime)
          if (e == 'weixin') {
            this.weixinXD()
          } else if (e == 'zhifubao') {
            this.zhifubaoXD()
          }
        } else {
          console.log('出错了!')
        }
      })
    },
    weixin () {
      this.getcurrentDateLong()
      // 微信支付按钮绑定事件
      console.log('微信支付 开始下单')
      if (this.ids.length > 0) {
        let str = ''
        for (let i = 0; i < this.ids.length; i++) {
          str = str + this.ids[i] + ','
        }
        str = str.substring(0, str.length - 1)
        console.log('str' + str)
        this.event_id = str
      }
      this.requestSecretEndTime = window.sessionStorage.getItem('requestSecretEndTime')
      if (this.requestSecretEndTime == 'underfind' || this.requestSecretEndTime == '' || this.requestSecretEndTime == null) {
        this.getrequestSecret('weixin')
      } else {
        if (this.currentDateLong < this.requestSecretEndTime) {
          this.weixinXD()
        } else {
          this.getrequestSecret('weixin')
        }
      }
    },
    zhifubaoXD () {
      console.log('支付宝支付 开始下单')
      this.requestSecret = window.sessionStorage.getItem('requestSecret')
      if (this.isGongkai == '公开') {
        this.isNiming = 2
      } else {
        this.isNiming = 1
      }
      if (this.$route.query.witchOne == 'piliang') {
        this.ids = this.$route.query.ids
        // this.money = this.$route.query.money
        console.log(this.ids)
        console.log(this.money / this.ids.length)
        http.post(CONSTANT.BATCH_ADD, {
          money: this.money / this.ids.length,
          ids: this.ids,
          event_id: this.ids,
          userId: this.userId,
          isNiming: this.isNiming
        }, (res) => {
          console.log(res)
          this.product_id = res.obj.product_id

          this.$router.push({path: '/alipayTips', query: {product_id: this.product_id, requestSecret: this.requestSecret}})
          // window.location.href = 'http://www.qqchou.org/wx/alipayTips.html?id=' + this.id
          // this.$router.push({path: '/alipayTips', query: {id: this.id}})
        })
      } else {
        var type = 0
        var eventid = ''
        if (this.$route.query.type) {
          console.log('一对一捐助')
          type = 1
          eventid = this.$route.query.student_id
        } else {
          eventid = this.event_id
        }
        if (!this.is_together) {
          this.is_together = 0;
        }
        http.post(CONSTANT.RECEIPT_ADD, {
          money: this.money,
          event_id: eventid,
          userId: this.userId,
          isNiming: this.isNiming,
          together_id: this.together_id,
          is_together:this.is_together,
          type: type
        }, (res) => {
          console.log(res)
          this.product_id = res.obj.product_id
          this.receiptId = res.obj.receiptId
          if (this.$route.query.type) {
            console.log('一对一捐助')
            type = 1
            eventid = this.$route.query.student_id
            var oname = this.$route.query.name
            var oidCard = this.$route.query.idCard
            var otelephone = this.$route.query.telephone
            var ocontent = this.$route.query.content
            var oaddress = this.$route.query.address
            if (typeof oname == 'undefined') {
              oname = ''
            }
            if (typeof oidCard == 'undefined') {
              oidCard = ''
            }
            if (typeof otelephone == 'undefined') {
              otelephone = ''
            }
            if (typeof ocontent == 'undefined') {
              ocontent = ''
            }
            if (typeof oaddress == 'undefined') {
              oaddress = ''
            }
            http.post(CONSTANT.USER_WORD, {userId: this.userId, name: oname, idCard: oidCard, telephone: otelephone, address: oaddress, student_id: eventid, content: ocontent}, (res) => {
              console.log('liuyan', res)
            })
          } else {
            var rname = this.$route.query.name
            var ridCard = this.$route.query.idCard
            var rtelephone = this.$route.query.telephone
            var rcontent = this.$route.query.content
            var raddress = this.$route.query.address
            if (typeof rname == 'undefined') {
              rname = ''
            }
            if (typeof ridCard == 'undefined') {
              ridCard = ''
            }
            if (typeof rtelephone == 'undefined') {
              rtelephone = ''
            }
            if (typeof rcontent == 'undefined') {
              rcontent = ''
            }
            if (typeof raddress == 'undefined') {
              raddress = ''
            }
            http.post(CONSTANT.USER_MESSAGE, {receiptId: this.receiptId, userId: this.userId, name: rname, idCard: ridCard, telephone: rtelephone, address: raddress, event_id: this.event_id, content: rcontent}, (res) => {
              console.log(res)
            })
            eventid = this.event_id
          }
          // this.zhifubaoZF()
          this.$router.push({path: '/alipayTips', query: {product_id: this.product_id, requestSecret: this.requestSecret}})
          // window.location.href = 'http://www.qqchou.org/wx/alipayTips.html?id=' + this.id
          // this.$router.push({path: '/alipayTips', query: {id: this.id}})
        })
      }
    },
    zhifubaoZF () {
      // http.post('http://etzx.hztangong.com/api', {'appKey': '402880e75f1520d3015f152167180000', 'requestSecret': this.requestSecret, 'type': '11', product_id: this.product_id, openid: this.openid, callBackUrl: CONSTANT.RECEIPT_ACHIEVE, 'orderInfo': '{"count": 1,"product_id":"' + this.event_id + '", "product_name": "' + this.theme + '","product_detail": "' + this.eventAbstract + '","price":' + this.money + '}'}, (res) => {
      //   console.log(res)
      //   if (res.code == 200) {
      //     console.log('下单返回id后 调用接口')
      //   } else {
      //     alert('提交订单失败！')
      //   }
      // })
    },
    zhifubao () {
      this.getcurrentDateLong()
      // 支付宝按钮绑定事件
      this.requestSecretEndTime = window.sessionStorage.getItem('requestSecretEndTime')
      console.log(this.requestSecretEndTime)
      if (this.requestSecretEndTime == 'underfind' || this.requestSecretEndTime == '' || this.requestSecretEndTime == null) {
        this.getrequestSecret('zhifubao')
      } else {
        if (this.currentDateLong < this.requestSecretEndTime) {
          this.zhifubaoXD()
        } else {
          this.getrequestSecret('zhifubao')
        }
      }
    },
    comeBack () {
      window.history.go(-1)
    }
  }
}
